﻿//Plugin_Warranty
//Copyright (c) 2011 by Mattias Benninge

//This is a plugin for SCCM Client Center (SMSCliCtrV2 by Roger Zander)

//This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or any later version. 
//This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 
//GNU General Public License: http://www.gnu.org/licenses/gpl.html

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Diagnostics;
using System.Management;
using System.IO;
using smsclictr.automation;
using Microsoft.Win32;
using System.Web.Services.Protocols;
using System.Web.Services;
using System.Xml.Serialization;

namespace SMSCliCtrV2
{
    public partial class MainForm : Form
    {
        private ListViewColumnSorter lvwWarranty;
        private bool Warranty;

        public MainForm()
        {

            InitializeComponent();
            
            toolStripProgressBar1.Visible = true;

            lvwWarranty = new ListViewColumnSorter();

            this.lv_warranty.ListViewItemSorter = lvwWarranty;

            Type t = System.Reflection.Assembly.GetEntryAssembly().GetType("SMSCliCtrV2.Common", true, true);
            System.Reflection.PropertyInfo pInfo = t.GetProperty("Hostname");
            System.Reflection.PropertyInfo pmScope = t.GetProperty("mScope");

            string sHost = (string)pInfo.GetValue(null, null);
            ManagementScope mScope = (ManagementScope)pmScope.GetValue(null, null);

            tb_computername.Text = sHost;

            Warranty = false;

            try
            {
                WMIProvider wmiProvider = new WMIProvider(mScope.Clone());
                SMSClient client = new SMSClient(wmiProvider);
                WMIProvider oWMIProvider = new WMIProvider(client.Connection.mScope.Clone());
                oWMIProvider.mScope.Path.NamespacePath = @"\root\cimv2";
                
                ManagementObjectCollection MOC = oWMIProvider.ExecuteQuery("SELECT * FROM Win32_BIOS");
                foreach (ManagementObject MO in MOC)
                {
                    tb_servicetag.Text = MO["SerialNumber"].ToString();
                }

                ManagementObjectCollection MOC2 = oWMIProvider.ExecuteQuery("SELECT * FROM Win32_ComputerSystem");
                foreach (ManagementObject MO in MOC2)
                {
                    string sManufacturer = MO["Manufacturer"].ToString();
                    Warranty = sManufacturer.Contains("Dell");
                    if (!Warranty)
                        lb_unsupported.Text = "The system you queried is a " + sManufacturer;
                }

            }
            catch 
            { 
            }



            if (Warranty)
            {
                try
                {
                    Plugin_Warranty.com.dell.xserv.AssetService proxy = new Plugin_Warranty.com.dell.xserv.AssetService();



                    Guid sGUID = new Guid("11111111-1111-1111-1111-111111111111"); ;


                    Plugin_Warranty.com.dell.xserv.Asset[] sOutput = proxy.GetAssetInformation(sGUID, "Dell Warranty Tool", tb_servicetag.Text);

                    tb_shipdate.Text = sOutput[0].AssetHeaderData.SystemShipDate.ToString();
                    tb_model.Text = sOutput[0].AssetHeaderData.SystemModel.ToString();
                    tb_id.Text = sOutput[0].AssetHeaderData.SystemID.ToString();
                    tb_type.Text = sOutput[0].AssetHeaderData.SystemType.ToString();

                    object[] eData = sOutput[0].Entitlements;
                    foreach (Plugin_Warranty.com.dell.xserv.EntitlementData ed in eData)
                    {
                        ListViewItem lvi_warranty = new ListViewItem(new string[] { ed.EntitlementType.ToString(), ed.EndDate.ToString(), ed.StartDate.ToString(), ed.DaysLeft.ToString(), ed.Provider, ed.ServiceLevelCode, ed.ServiceLevelDescription });
                        if (!IsInCollection(lvi_warranty))
                        lv_warranty.Items.Add(lvi_warranty);
                    }


                }
                catch (System.Exception ex)
                {
                    toolStripStatusLabel1.Text = ex.Message;
                    toolStripProgressBar1.Visible = false;
                }
            }
            toolStripProgressBar1.Visible = false;
        }

        private bool IsInCollection(ListViewItem lvi)
        {
            foreach (ListViewItem item in lv_warranty.Items)
            {
                bool subItemEqualFlag = true;
                for (int i = 0; i < item.SubItems.Count; i++)
                {
                    string sub1 = item.SubItems[i].Text;
                    string sub2 = lvi.SubItems[i].Text;
                    if (sub1 != sub2)
                    {
                        subItemEqualFlag = false;
                    }
                }
                if (subItemEqualFlag)
                    return true;
            }
            return false;

        }


        /// <summary>
        /// Copy all selected Items to ClipBoard on (Ctrl+C)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lv_CopySelected_KeyDown(object sender, KeyEventArgs e)
        {
            ListView oSource = sender as ListView;
            if (e.Control && e.KeyCode == Keys.C)
            {
                if (oSource.SelectedItems.Count > 0)
                {
                    StringBuilder buffer = new StringBuilder();
                    /*for (int i = 0; i < oSource.Columns.Count; i++)
                    {
                        buffer.Append(oSource.Columns[i].Text);
                        buffer.Append("\t");
                    }
                    buffer.Append("\n"); */
                    foreach (ListViewItem lvItem in oSource.SelectedItems)
                    {
                        for (int j = 0; j < oSource.Columns.Count; j++)
                        {
                            buffer.Append(lvItem.SubItems[j].Text);
                            buffer.Append("\t");
                        }
                        buffer.Append("\r\n");
                    }
                    Clipboard.SetText(buffer.ToString());
                }
            }
        }

        private void lv_warranty_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            // Determine if clicked column is already the column that is being sorted. 
            if (e.Column == lvwWarranty.SortColumn)
            {
                // Reverse the current sort direction for this column. 
                if (lvwWarranty.Order == SortOrder.Ascending)
                {
                    lvwWarranty.Order = SortOrder.Descending;
                }
                else
                {
                    lvwWarranty.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending. 
                lvwWarranty.SortColumn = e.Column;
                lvwWarranty.Order = SortOrder.Ascending;
            }
            // Perform the sort with these new sort options. 
            lv_warranty.Sort();
        }

     }
}
